import os.path, time, json

class LocalFileSystem:
	def __init__(self):
		self._cache={}
	def dump(self, fp):
		json.dump(self._cache, fp)
	def load(self, fp):
		self._cache=json.load(fp)
	def getInfo(self, name):
		if self._cache.has_key(name):
			return self._cache[name]
		else:
			return {"modified": 0, "watched": 0, "exists": False}

class SacvoyageFileSystem:
	def __init__(self, url, user, password):
		pass
	def getInfo(self, name):
		pass


def synchronize(local, remote):
	local.update();




class DirWatch:
	def __init__(self, rootDir='.', cache={}):
		self._rootDir=os.path.abspath(rootDir);
		self._cache=cache

	def run(self):
		while True:
			self._watch()
			time.sleep(1)

	def _watch(self):
		watched=[]
		for root, dirs, files in os.walk(self._rootDir):
			for f in files:
				fileName=os.path.join(root, f)
				watched.append(fileName)
				fileInfo={
					"modified": int(os.path.getmtime(fileName)), 
					"watched": int(time.time()),
					"exists": True
				}
				if self._cache.has_key(fileName):
					if self._cache[fileName]["modified"]!=fileInfo["modified"] or self._cache[fileName]["exists"]!=fileInfo["exists"]:
						self._notifyChanged(fileName, fileInfo)
				else:
					self._notifyCreated(fileName, fileInfo)
				self._cache[fileName]=fileInfo
		for fileName in set(self._cache.keys())-set(watched):
			fileInfo=self._cache[fileName]
			fileInfo["exists"]=False
			self._notifyDeleted(fileName, fileInfo)
			del self._cache[fileName]
			
	def _notifyChanged(self, fileName, fileInfo):
		print fileName, "changed"

	def _notifyCreated(self, fileName, fileInfo):
		print fileName, "created"

	def _notifyDeleted(self, fileName, fileInfo):
		print fileName, "deleted"


local=deleted.update(actual)

for fileName in set(local.keys())-set(remote.keys()):
	upload(local[fileName])

for fileName in set(remote.keys())-set(local.keys()):
	download(local[fileName])

for fileName in remote.keys().intersection(local.keys()):
	if remote[fileName]['modified']<local[fileName]['modified']:
		upload(fileName)
	elif if remote[fileName]['modified']>local[fileName]['modified']:
		download(fileName)
	


def updateLocalCache(cache, config):
		watched=[]
		for root, dirs, files in os.walk(config.rootDir):
			for f in files:
				fileName=os.path.join(config.rootDir, f)
				watched.append(fileName)
				fileInfo={
					"_rev": int(os.path.getmtime(fileName)), 
					"watched": int(time.time()),
					"_deleted": False
				}
		for fileName in set(self._cache.keys())-set(watched):
			if not fileInfo['_deleted']:
				fileInfo["_deleted"]=True
				fileInfo["_rev"]=fileInfo["watched"]

def updateSacvoyageCache(cache, config):
	query={"select": {"_id": True, "_rev": True}, "filter": {"_not": {"chunk": True }}}
	for document in config.sacvoyage.find(query):
		cache[document["_id"]]={"_rev": document["_rev"], "_deleted": False}
	query={"select": {"_id": True, "_rev": True}, 'filter': {'_deleted': True}}
	for document in config.sacvoyage.find(query):
		if document['_id'] in cache and cache[document['_id']]['_rev']>document['_rev']:
			cache[document["_id"]]={"_rev": document["_rev"], "_deleted": True}
		
	# find()
	# find({"status": "stale", "filter": {"_deleted": True}})


def fillCache(rootDir):
	cache={}
	for root, dirs, files in os.walk(os.path.abspath(rootDir)):
		for f in files:
			fileName=os.path.join(root, f)
			fileInfo={
				"modified": int(os.path.getmtime(fileName)), 
				"watched": int(time.time())
			}
			cache[fileName]=fileInfo
	return cache

watch=DirWatch('.', fillCache('.'));
watch.run();
